﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.DirectX;
using BurningSphere.Simulator.Properties;
using Microsoft.DirectX.Direct3D;
using System.IO;

namespace BurningSphere.Simulator.Controls
{
	/// <summary>
	/// A shape projection is a mechanism for managing the iteration
	/// through the points during laser play-back.  Pass to the laser
	/// </summary>
	public class ShapeProjection : LaserControl
	{
		string fileName;
		int index = -1;
		float scale = 1.0f;
		Shape shape;

		Matrix laserMatrix;

		/// <summary>
		/// Ctor
		/// </summary>
		public ShapeProjection()
		{
		}

		/// <summary>
		/// Ctor
		/// </summary>
		/// <param name="shape">Shape</param>
		public ShapeProjection(Shape shape)
		{
			this.shape = shape;
		}

		/// <summary>
		/// File name
		/// </summary>
		public string Filename
		{
			get
			{
				return fileName;
			}
			set
			{
				fileName = value;
				Load();
			}
		}

		/// <summary>
		/// Load the shape
		/// </summary>
		private void Load()
		{
			if (Path.GetExtension(fileName).ToLower() == ".raw")
			{
				shape = new ShapeRAW();
				shape.Load(fileName);
			}
			else
			{
				shape = new Shape();
				shape.Load(fileName);
			}
		}

		/// <summary>
		/// Reset interation
		/// </summary>
		public void Reset()
		{
			index = -1;
		}

		/// <summary>
		/// Move to next point in shape
		/// </summary>
		/// <returns></returns>
		public override bool MoveNext()
		{
			index++;
			if (index == shape.Points.Count)
			{
				return false;
			}
			return true;
		}

		/// <summary>
		/// Current point in shape
		/// </summary>
		public Vector2 Current
		{
			get
			{
				return shape.Points[index];
			}
		}

		/// <summary>
		/// Scale
		/// </summary>
		public float Scale
		{
			get
			{
				return scale;
			}
			set
			{
				scale = value;
			}
		}

		/// <summary>
		/// This class is also a LaserControl, and can set
		/// the position of the laser.  
		/// </summary>
		public override Matrix LaserMatrix
		{
			get
			{
				return laserMatrix;
			}
		}

		/// <summary>
		/// Update
		/// </summary>
		/// <param name="matrix"></param>
		public override void Update(Matrix matrix)
		{
			Matrix rotateY = Matrix.RotationY(Geometry.DegreeToRadian(Current.X * Scale) * 180.0f);
			Matrix rotateX = Matrix.RotationX(Geometry.DegreeToRadian(Current.Y * Scale) * -180.0f);

			laserMatrix = rotateX * rotateY * matrix; // possible order issue
		}
	}
}
